import type { LoginFormType } from '../api/interface'

import { Form, Input, Button, Space, Tabs, Radio } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { observer, useLocalObservable } from 'mobx-react'
import { history } from 'umi'
import { useRef, useState, useEffect } from 'react'

import Store from './store'
import ContentBgImg from '@/static/login/login_bg.png'
import FrameImg from '@/static/login/frame.png'
import styles from './index.module.less'
import NavBar from '@/components/Global/NavBar'
import HelmetWrap from '@/layouts/components/Helmet'

import { SMSCaptcha } from './SMSCaptcha'
import { EmbedCaptcha } from './EmbedCaptcha'
import type { InputRef } from 'antd-mobile/es/components/input'
import { stores } from '@/stores'

const LoginType = {
    personal: 1,
    org: 2,
}

const Login = () => {
    const [form] = Form.useForm()
    const [visible, setVisible] = useState(false)
    const phoneRef = useRef<InputRef>(null)
    const [loginType, setLoginType] = useState<keyof typeof LoginType>('personal')
    const store = useLocalObservable(() => new Store())
    const [windowWidth, setWindowWidth] = useState(window.innerWidth)

    useEffect(() => {
        const handleResize = () => {
            setWindowWidth(window.innerWidth)
        }

        window.addEventListener('resize', handleResize)

        return () => {
            window.removeEventListener('resize', handleResize)
        }
    }, [])

    const isSMSLoginValid = Number(stores.siteStore.siteData.sms_switch) === 1

    // const renderLabel = (text: string) => {
    //     return <span className={styles.formLabel}>{text}</span>
    // }

    const onSubmit = async (value: LoginFormType) => {
        store.login({
            ...value,
        })
    }

    const onCertificateSearch = () => {
        history.push({ pathname: '/certificate/search' })
    }

    return (
        <div className={styles.page}>
            <NavBar title={store.siteInfo.website} />
            <HelmetWrap />

            <main>
                <header>
                    <img className={styles.ctxBgImg} src={ContentBgImg} />
                    <img className={styles.frameImg} src={FrameImg} />
                    <span className={styles.welcome}>欢迎登录</span>
                    <span className={styles.title}>{store.siteInfo.website}</span>
                </header>

                <div className={styles.content}>
                    <Tabs
                        defaultActiveKey={loginType}
                        onChange={key => {
                            form.resetFields()
                            store.updateRequestId(undefined)
                            setLoginType(key as keyof typeof LoginType)
                            form.setFieldValue('type', LoginType[key as keyof typeof LoginType])
                        }}
                    >
                        <Tabs.Tab title="个人登录" key="personal" />
                        <Tabs.Tab title="组织机构登录" key="org" />
                    </Tabs>
                    <Form
                        form={form}
                        style={{ '--border-top': 'none', '--border-bottom': 'none' }}
                        onFinish={onSubmit}
                        requiredMarkStyle="text-optional"
                        initialValues={{ type: LoginType.personal }}
                        footer={
                            <>
                                {isSMSLoginValid && loginType === 'personal' && (
                                    <div className={styles.forgetBtn}>
                                        <a onClick={() => history.push('/forget')}>忘记密码？</a>
                                    </div>
                                )}

                                <Space direction="vertical" style={{ width: '100%' }}>
                                    <Button
                                        block
                                        type="submit"
                                        color="primary"
                                        className={styles.submitBtn}
                                    >
                                        登录
                                    </Button>

                                    <Button
                                        block
                                        fill="none"
                                        style={{ color: '#1ebead' }}
                                        onClick={onCertificateSearch}
                                    >
                                        证书查询
                                    </Button>
                                </Space>
                            </>
                        }
                    >
                        <Form.Item name="type" hidden>
                            <Radio />
                        </Form.Item>

                        <Form.Item
                            name="user_phone"
                            rules={[{ required: true, message: '请输入账号' }]}
                        >
                            <Input placeholder="请输入账号" ref={phoneRef} />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[{ required: true, message: '请输入密码' }]}
                        >
                            <div className={styles.password}>
                                <Input
                                    className={styles.input}
                                    placeholder="请输入密码"
                                    type={visible ? 'text' : 'password'}
                                />
                                <div className={styles.eye}>
                                    {!visible ? (
                                        <EyeInvisibleOutline onClick={() => setVisible(true)} />
                                    ) : (
                                        <EyeOutline onClick={() => setVisible(false)} />
                                    )}
                                </div>
                            </div>
                        </Form.Item>
                        {isSMSLoginValid && loginType === 'personal' && (
                            <Form.Item
                                name="sms_code"
                                extra={
                                    <SMSCaptcha
                                        phoneRef={phoneRef}
                                        onResultUpdate={result => {
                                            if (result?.Result) {
                                                store.updateRequestId(result.RequestId)
                                            }
                                        }}
                                    />
                                }
                            >
                                <Input placeholder="请输入验证码" />
                            </Form.Item>
                        )}
                        {isSMSLoginValid && loginType === 'org' && (
                            <div style={{ transform: `scale(${windowWidth / 375 - 0.05})` }}>
                                <EmbedCaptcha
                                    onResultUpdate={result => {
                                        if (result?.Result) {
                                            store.updateRequestId(result.RequestId)
                                        }
                                    }}
                                />
                            </div>
                        )}
                    </Form>
                </div>

                <footer>
                    <div className={styles.info}>
                        <span>© {store.siteInfo.copyright || '-'} 版权所有</span>
                        <span>© {store.siteInfo.technology || '-'} 技术支持</span>
                    </div>
                </footer>
            </main>
        </div>
    )
}

export default observer(Login)
